<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :on-preview="onPreview"
      :class="{hiddenImg:fileList.length>0}"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="httpRequest"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="isShowProgress" style="width:143px;margin-top:10px" :text-inside="true" :stroke-width="26" :percentage="percent" />
    <el-dialog title="预览" :visible="isShowDialog" @close="isShowDialog = flase">
      <el-row type="flex" justify="center">
        <img :src="PreviewImg" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID95l46sNcaHhrkMhma7NM4VifLksiIbeQ',
  SecretKey: 'WmlUw83h4B0Zqqb7NL3UeX9yYrsd7JFu'
})
export default {
  data() {
    return {
      isShowProgress: false,
      percent: 0,
      PreviewImg: '',
      isShowDialog: false,
      fileList: [
        // { url: 'https://tse4-mm.cn.bing.net/th/id/OIP-C.G0D8-wu-AFXefFljUpENWAHaGT?w=239&h=203&c=7&r=0&o=5&dpr=1.42&pid=1.7' }
      ]
    }
  },
  methods: {
    onPreview(file) {
      console.log(file)
      this.PreviewImg = file.url
      this.isShowDialog = true
    },
    onRemove(file, newFileList) {
      this.fileList = newFileList
    },
    onChange(file, newFilelist) {
      this.fileList = newFilelist
    },
    beforeUpload(file) {
      console.log('上传前', file)
      const typeList = ['image/jpeg', 'image/png', 'image/gif']
      if (!typeList.includes(file.type)) {
        this.$message.error('必须 jpg,png,gif 格式')
        return false
      }
      const maxSize = 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('大小不能超过 1 兆')
        return false
      }
    },
    httpRequest(params) {
      console.log('上传后')
      this.isShowProgress = true
      cos.putObject({
        Bucket: '187976-1308177479', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(77, JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(78, err || data)
        setTimeout(() => {
          this.isShowProgress = false
        }, 1000)
        console.log(this.fileList)
        this.fileList[0].url = 'http://' + data.Location
        this.fileList[0].status = 'success'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.hiddenImg{
::v-deep .el-upload--picture-card{
    display: none;
  }
}
::v-deep .el-upload-list__item-actions{

   object-fit:cover;
}
</style>
